package cn.ewan.cloud.tenant.data.router.example.controller;

import cn.ewan.cloud.common.support.Log;
import cn.ewan.cloud.tenant.data.router.core.common.util.TenantLog;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author lgh
 * @date 2022/12/19 11:03
 */
@Component
public class AsyncTest {

    @Resource
    TestFeign testFeign;

    public static ExecutorService ttlExecutorService = Executors.newSingleThreadExecutor(new ThreadFactory() {
        AtomicInteger atomicInteger = new AtomicInteger(0);

        @Override
        public Thread newThread(Runnable r) {
            Thread thread = new Thread(r, "test_" + atomicInteger.getAndIncrement());
            return thread;
        }
    });


    @Async
    public Future<String> routeAsyncTest(Integer appId) {
        TenantLog.log("方法=routeAsyncTest");
        String s = testFeign.routeTest(appId);
        return new AsyncResult<>(s);
    }

    public Future<String> routeAsyncTest1(Integer appId) {
        Log.NORMAL.info("method=action before threadPool,threadId={},threadName={}", Thread.currentThread().getId(), Thread.currentThread().getName());
//        ExecutorService ttlExecutorService = TtlExecutors.getTtlExecutorService(Executors.newFixedThreadPool(8));
        Future<String> submit = ttlExecutorService.submit(() -> {
            return testRouteAsyncTest1(appId);
        });
        return submit;
    }


    public Future<String> asyncExecutorRestore() {
        Future<String> submit = ttlExecutorService.submit(() -> {
            TenantLog.log("asyncExecutorRestore");
            return "finish";
        });
        return submit;
    }


    private String testRouteAsyncTest1(Integer appId) {
        return testFeign.routeTest(appId);
    }
}
